package main

import (
	"flag"
	"fmt"
	"github.com/nats-io/go-nats"
	"log"
)

const (
	//url   = "nats://192.168.3.125:4222"
	url1 = nats.DefaultURL
)

var (
	nConn1 *nats.Conn
	err1   error
)

func init() {
	if nConn1, err1 = nats.Connect(url1); checkErr2(err1) {
	}
}
func main() {
	ServerListen1()
}

func ServerListen1() {
	var (
		servername = flag.String("servername", "Y", "name for server")
		queueGroup = flag.String("group", "t1", "group name for Subscribe")
		subj       = flag.String("subj", "test_data", "subject name")
	)
	flag.Parse()

	mode := "queue"
	if *queueGroup == "" {
		mode = "pub/sub"
	}
	log.Printf("Server[%v] Subscribe Subject[%v] in [%v]Mode", *servername, *subj, mode)

	startService1(*subj, *servername+" worker1", *queueGroup)
	//startService1(*subj, *servername+" worker2", *queueGroup)
	//startService1(*subj, *servername+" worker3", *queueGroup)

	nConn1.Flush()
	select {}
}

//receive message
func startService1(subj, name, queue string) {
	go async1(nConn1, subj, name, queue)
}

func async1(nc *nats.Conn, subj, name, queue string) {
	replyMsg := name + " Received a msg"
	if queue == "" {
		_, err1 = nc.Subscribe(subj, func(msg *nats.Msg) {
			err1 = nc.Publish(msg.Reply, []byte(replyMsg))
			fmt.Println(name, "成功收到的消息为:", string(msg.Data))
		})
	} else {
		_, err1 = nc.QueueSubscribe(subj, queue, func(msg *nats.Msg) {
			err1 = nc.Publish(msg.Reply, []byte(replyMsg))
			fmt.Println(name, "成功收到的queue消息为: ", string(msg.Data))
		})
	}

}

func checkErr2(err error) bool {
	if err != nil {
		log.Println(err)
		return false
	}
	return true
}
